export function omitFilterEmptyField(obj) {
	return JSON.parse(JSON.stringify(obj), (key, value) => {
		if (typeof value !== 'object') return value;

		if (Array.isArray(value) && value.length === 0) return undefined;

		return Object.keys(value).length === 0 ? undefined : value;
	});
}

export default function searchStringBuilder(currentSearch = '', fields = {}) {
	const next = {
		...fields,
		...(fields.filter
			? { filter: omitFilterEmptyField(fields.filter) || {} }
			: {}),
	};
	return Object.entries(next).reduce((search, [name, value]) => {
		name in next && value === undefined
			? search.delete(name)
			: search.set(
					name,
					typeof value === 'object' ? JSON.stringify(value) : value
			  );

		return search;
	}, new URLSearchParams(currentSearch));
}
